﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;

namespace SelfManagement.Utility.Extensions
{
    public static class JsonExtensions
    {
        public enum PropertyNaming
        {
            Default = 0,
            /// <summary>
            /// 首字母小写
            /// </summary>
            CamelCase = 1
        }

        public static string ToJson(this object data, PropertyNaming propertyNaming = PropertyNaming.Default)
        {
            if (data == null)
            {
                return string.Empty;
            }

            var settings = new JsonSerializerSettings();

            if (propertyNaming == PropertyNaming.CamelCase)
            {
                settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }

            settings.Converters.Add(new StringEnumConverter());

            return JsonConvert.SerializeObject(data, settings);
        }

        public static T ToObject<T>(this string source)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                return default(T);
            }

            return JsonConvert.DeserializeObject<T>(source);
        }

        public static T ToObject<T>(this string source, PropertyNaming propertyNaming = PropertyNaming.Default)
        {
            if (string.IsNullOrEmpty(source))
            {
                return default(T);
            }

            var settings = new JsonSerializerSettings();

            if (propertyNaming == PropertyNaming.CamelCase)
            {
                settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }

            settings.Converters.Add(new StringEnumConverter());

            return JsonConvert.DeserializeObject<T>(source, settings);
        }

    }
}
